<?php

namespace App\Providers;

use App\App\Services\Web\UserService;
use App\Contracts\Repositories\ActivityModelRepository;
use App\Contracts\Repositories\ActivityModelTemplateRepository;
use App\Models\Activity\Activity;
use App\Morefun\Shaking\RedisSynchronizer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Ramsey\Uuid\Uuid;
use Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->extendValidator();

        View::composer('*', function ($view) {
            $user = $this->app->make(UserService::class);

            $profile = json_encode([
                'user-id'    => $user->getUserId(),
                'group-code' => $user->getGroupCode(),
            ]);

            $view->with('___profile', $profile);
        });
    }

    private function extendValidator()
    {
        Validator::extend('uuid', function ($attribute, $value, $parameters) {
            return Uuid::isValid($value);
        });

        Validator::extend('float', function ($attribute, $value, $parameters) {
            return is_float($value);
        });

        Validator::extend('mobile', function ($attribute, $value, $parameters) {
            return preg_match('/^1[3457689]\d{9}$/', $value) > 0;
        });

        Validator::extend('phone', function ($attribute, $value, $parameters) {
            return (preg_match('/^([0-9]{3,4}-)?[0-9]{7,8}$/', $value) > 0) ||
                (preg_match('/^1[3456789]\d{9}$/', $value) > 0);
        });

        Validator::extend('password', function ($attribute, $value, $parameters) {
            // length of password should range [6, 18]
            $len = strlen($value);

            return $len >= 6 && $len <= 18;
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(
            ActivityModelRepository::class,
            \App\Models\ActivityModel\ActivityModelRepository::class
        );
        $this->app->singleton(
            ActivityModelTemplateRepository::class,
            \App\Models\ActivityModelTemplate\ActivityModelTemplateRepository::class
        );
    }

    public function provides()
    {
        return [
            ActivityModelRepository::class,
            ActivityModelTemplateRepository::class
        ]; // TODO: Change the autogenerated stub
    }
}
